<script setup>
import { ref, computed, onMounted } from 'vue';
import { Lunar } from 'lunar-javascript';
import {
  NAvatar,
  NButton,
  NFlex,
  NForm,
  NFormItem,
  NImage,
  NInput,
  NSelect,
  NTabPane,
  NTabs,
  NTag,
  useMessage
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import api from '@/api'
import default_image from "@/assets/images/mz.jpg";
import {getToken, renderIcon} from "@/utils";
import TheIcon from "@/components/icon/TheIcon.vue";
import {useCRUD} from "@/composables";
import CrudModal from "@/components/table/CrudModal.vue";
const base_path = import.meta.env.VITE_BASE
const message = useMessage()

const {
  modalVisible,
  modalAction,
  modalTitle,
  modalLoading,
  handleAdd,
  handleDelete,
  handleEdit,
  handleSave,
  modalForm,
  modalFormRef,
} = useCRUD({
  name: '预约',
  initForm: {},
  doCreate: api.createAppointment,
  doDelete: api.deleteAppointment,
  doUpdate: api.editAppointment,
  refresh: () => on_ref(),
})

const props = defineProps({
  infoData: {
    type: Object,
    required: true
  }
});

const currentDate = ref(new Date());
const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
const newTodoText = ref('');
const newTodoDate = ref('');
const draggedTodo = ref(null);

const data = reactive({
  card_loading:false,
  select_customer:{
    name:"未选择",
    card_number:"--",
    user_level_name:"--",
    mobile:"--",
    bi_date:"--",
    sex:"--",
    hkqd:"--",
    age:"--",
    created_at:"--",
    last_come:"--",
    record_hobby:[],
    totals:{
    weimei:0,
    cdp:0,
    fujia:0,
    other:0,
    buy_money:0,
    cases:0,
    appoint_count:0,
    return_count:0,
    operation_count:0,
    face_count:0,
    test_count:0,
    having_customers:0,
    customers_level5:0

    }
    },
  todos : [],
  startDate:"",
  endDate:"",
  meeting_users:[],
  projects:[],
  search_loading:false
});

onMounted(() => {
  newTodoDate.value = formatDate(new Date());
  data.select_customer = props.infoData
  on_ref()
  api.getMeetingUsers({types:2}).then((res) => {
     data.meeting_users = res.data.list
  })

  api.getProjects().then((res) => {
     data.projects = res.data.list
  })
})

function on_ref(){
  get_appointments()
  modalVisible.value = false
}

function get_appointments(){
   data.card_loading = true
   api.getAppointment({
    user_id:data.select_customer.user_id,
    startDate:data.startDate,
    endDate:data.endDate,
    type:88
  }).then((res) => {
     data.todos = res.data.items
     data.card_loading = false
  })
}


// 生成日历天数
const calendarDays = computed(() => {
const year = currentDate.value.getFullYear();
const month = currentDate.value.getMonth();
const firstDayOfMonth = new Date(year, month, 1);
const lastDayOfMonth = new Date(year, month + 1, 0);
const daysInMonth = lastDayOfMonth.getDate();
const startDayOfWeek = firstDayOfMonth.getDay();

const days = [];

// 添加上个月的最后几天
const prevMonthLastDay = new Date(year, month, 0).getDate();
for (let i = startDayOfWeek - 1; i >= 0; i--) {

  const date = new Date(year, month - 1, prevMonthLastDay - i);
  if(i === startDayOfWeek){
    data.startDate = formatDate(date)
  }
  const lunar = Lunar.fromDate(date);
  days.push({
    date: formatDate(date),
    dayNumber: date.getDate(),
    lunarDay: lunar.getDayInChinese(), // 农历日
    lunarMonth: lunar.getMonthInChinese(), // 农历月
    isCurrentMonth: false,
    isToday: isSameDay(date, new Date())
  });
  // data.startDate = formatDate(date)
}

// 添加当月的天数
for (let i = 1; i <= daysInMonth; i++) {
const date = new Date(year, month, i);
const lunar = Lunar.fromDate(date);
days.push({
  date: formatDate(date),
  dayNumber: date.getDate(),
  lunarDay: lunar.getDayInChinese(), // 农历日
  lunarMonth: lunar.getMonthInChinese(), // 农历月
  isCurrentMonth: true,
  isToday: isSameDay(date, new Date()),
  isLunarFestival: lunar.getFestivals().length > 0, // 是否是农历节日
  festivals: lunar.getFestivals() // 农历节日列表
});
}

// 添加下个月的前几天
const daysToAdd = 42 - days.length;
for (let i = 1; i <= daysToAdd; i++) {

  const date = new Date(year, month + 1, i);
  if(i===1){
     data.endDate = formatDate(date)
  }
  const lunar = Lunar.fromDate(date);
  days.push({
    date: formatDate(date),
    dayNumber: date.getDate(),
    lunarDay: lunar.getDayInChinese(), // 农历日
    lunarMonth: lunar.getMonthInChinese(), // 农历月
    isCurrentMonth: false,
    isToday: isSameDay(date, new Date())
  });
  // data.endDate = formatDate(date)
}

return days;
});
// 当前月份和年份显示
const currentMonthYear = computed(() => {
  const options = { year: 'numeric', month: 'long' };
  return currentDate.value.toLocaleDateString('zh-CN', options);
});
// 可选择添加待办的日期
const selectableDates = computed(() => {
  return calendarDays.value
    .filter(day => day.isCurrentMonth)
    .map(day => ({
      date: day.date,
      displayDate: `${day.date} (${weekdays[new Date(day.date).getDay()]})`
    }));
});


// 导航方法
const prevMonth = () => {
  currentDate.value = new Date(
    currentDate.value.getFullYear(),
    currentDate.value.getMonth() - 1,
    1
  );
  on_ref()
};

const nextMonth = () => {
  currentDate.value = new Date(
    currentDate.value.getFullYear(),
    currentDate.value.getMonth() + 1,
    1
  );
  on_ref()
};

// 待办操作方法
const addTodo = () => {
  if (newTodoText.value.trim() && newTodoDate.value) {
    data.todos.push({
      id: Date.now(),
      text: newTodoText.value.trim(),
      date: newTodoDate.value,
    });
    newTodoText.value = '';
  }
  console.log(data.todos)
};

const getTodosForDate = (date) => {
  // 标准化输入的日期格式（确保格式一致）
  const normalizedInputDate = normalizeDate(date);

  return data.todos.filter(todo => {
    // 标准化待办事项中的日期格式
    const normalizedTodoDate = normalizeDate(todo.date);
    return normalizedTodoDate === normalizedInputDate;
  })
};

// 辅助函数：标准化日期格式（统一为YYYY-MM-DD，月份和日期带前导零）
const normalizeDate = (dateStr) => {
  if (!dateStr) return '';

  // 处理多种可能的日期格式：
  // 1. 2023-1-5 → 2023-01-05
  // 2. 2023/1/5 → 2023-01-05
  // 3. 2023.1.5 → 2023-01-05
  const date = new Date(dateStr.replace(/[/.]/g, '-'));

  // 如果日期无效，返回空字符串
  if (isNaN(date.getTime())) return '';

  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');

  return `${year}-${month}-${day}`;
};

// 拖拽方法
const handleDragStart = (event, todo) => {
  draggedTodo.value = todo;
  event.dataTransfer.setData('text/plain', todo.id);
};

const handleDragOver = (event) => {
  event.preventDefault();
};

const handleDrop = (event, targetDate) => {
  event.preventDefault();
  if (draggedTodo.value) {
    const todoIndex = data.todos.findIndex(t => t.id === draggedTodo.value.id);
    if (todoIndex !== -1) {
      data.todos[todoIndex].date = targetDate;
    }
    api.updateAppointment({
      id:draggedTodo.value.id,
      new_date:targetDate,
    }).then((res) => {
       message.success('移动到'+targetDate)
      on_ref()
    })

    draggedTodo.value = null;


  }
};

// 工具方法
const formatDate = (date) => {
  return date.toLocaleDateString('zh-CN').replace(/\//g, '-');
};

const isSameDay = (date1, date2) => {
  return date1.getFullYear() === date2.getFullYear() &&
         date1.getMonth() === date2.getMonth() &&
         date1.getDate() === date2.getDate();
};

function add_appointment(){
  handleAdd()
  modalForm.value.user_id = data.select_customer.user_id
  modalForm.value.color = "#d95b74"
  modalForm.value.type = 88
}

function search_project(query){
  data.search_loading = true
  api.getProjects({keyword:query}).then((res) => {
     data.projects = res.data.list
     data.search_loading = false
  })
}

function save_appointment(){
   modalForm.value.project_name = modalForm.value.project_id.map(id => {
    const project = data.projects.find(p => p.id === id)
    return project?.title || ''
  }).filter(Boolean)
  handleSave()
}

function del_appointment(){
  api.deleteAppointment({
    id: modalForm.value.id,
  }).then((res) => {
    message.success('已经取消')
    on_ref()
  })
}



</script>
<template>
  <n-card size="small" content-style="padding: 20px;" embedded  :bordered="false" :segmented="{content: true,footer: 'soft',}">
              <template #header><n-h6 prefix="bar" style="margin: 0;font-size: 18px">{{ currentMonthYear }}</n-h6></template>
              <template #header-extra>
                <n-button size="small" type="info" style="margin-left: 5px" @click="prevMonth">
                  <TheIcon icon="material-symbols:skip-previous-outline" :size="16" class="mr-5" />
                  上个月</n-button>
                <n-button size="small" type="info" style="margin-left: 5px" @click="nextMonth">
                  <TheIcon icon="material-symbols:skip-next-outline-rounded" :size="16" class="mr-5" />下个月</n-button>
                <n-button size="small" type="primary" style="margin-left: 5px" @click="add_appointment">
                  <TheIcon icon="material-symbols:add" :size="16" class="mr-5" />添加</n-button>
              </template>
              <div class="calendar-container">

              <n-scrollbar  style="max-height: calc(100vh - 210px);padding:0 0px 20px 0px">
                <n-spin :show="data.card_loading" style="--n-opacity-spinning:0.1;height: calc(100vh - 225px);">
                  <div class="calendar-grid">
                    <div class="weekday" v-for="day in weekdays" :key="day">{{ day }}</div>

                    <div
                      class="calendar-day"
                      v-for="day in calendarDays"
                      :key="day.date"
                      :class="{
                        'current-month': day.isCurrentMonth,
                        'today': day.isToday
                      }"
                      @dragover.prevent="handleDragOver($event, day.date)"
                      @drop="handleDrop($event, day.date)"
                    >
                      <div class="day-number" style="display: flex;justify-content: space-between">
                        <div style="background: #8945c3a3;width: 20px;height:20px;text-align: center;color: #fff;border-radius: 50%;font-size: 14px;">{{ day.dayNumber }}</div>
                        <div style="font-size: 10px;color: #6a6a6a;line-height: 20px;">{{ day.lunarDay  }}</div>
                      </div>
                      <div
                        class="todo-item"
                        v-for="todo in getTodosForDate(day.date)"
                        :key="todo.id"
                        draggable="true"
                        @dragstart="handleDragStart($event, todo)"
                        :style="'background:'+todo.color"
                      >
                        <div style="text-align: center;width: 100%;color:#fff" @click="handleEdit(todo)">
                          {{ todo.project_name }}<br>
                          <span style="font-size: 12px">{{ todo.longs }}min</span>
                          </div>
                      </div>
                    </div>
                  </div>
                </n-spin>
              </n-scrollbar>

  </div>
  </n-card>

  <n-drawer v-model:show="modalVisible" width="400px">
      <n-drawer-content title="抗衰计划" closable>
        <NForm
        ref="modalFormRef"
        label-placement="left"
        label-align="left"
        :label-width="80"
        :model="modalForm"
      >
          <NFormItem label="选择项目" path="project_id">
          <NSelect
              v-model:value="modalForm.project_id"
              :options="data.projects"
              placeholder="输入名称检索"
              filterable
              label-field="title"
              value-field="id"
              style="width: 100%"
              remote
              clearable
              multiple
              :loading="data.search_loading"
              @search="search_project"
            />


        </NFormItem>
        <NFormItem label="选择医生" path="doctor_id">
          <NSelect
              v-model:value="modalForm.doctor_id"
              :options="data.meeting_users"
              placeholder="选择医生"
              filterable
              label-field="name"
              value-field="id"
              style="width: 100%"
              multiple
            />
        </NFormItem>


          <NFormItem label="预约时间" path="appoint_time">
          <n-date-picker
            v-model:formatted-value="modalForm.appoint_time"
            type="datetime"
            clearable
            placeholder="请输入预约时间"
            style="width: 100%"
          />
        </NFormItem>

          <NFormItem label="预约时长" path="visit_date">
          <n-input-number min="10"  step="10" v-model:value="modalForm.longs" placeholder="请输入预约时长"/>
        </NFormItem>

          <NFormItem label="颜色设置" path="color">
          <n-color-picker :modes="['hex']"  v-model:value="modalForm.color" placeholder="颜色设置"/>
        </NFormItem>




      </NForm>
         <template #footer>
        <n-button type="primary"  @click="save_appointment">
          <TheIcon icon="material-symbols:save-sharp" :size="16" class="mr-5" />保存</n-button>

           <n-popconfirm @positive-click="del_appointment" v-if="modalForm.id>0">
        <template #trigger>
          <n-button type="error"   style="margin-left:10px">
            <TheIcon icon="material-symbols:contract-delete" :size="16" class="mr-5"/>
            删除
          </n-button>
        </template>
        确定要删除吗？
      </n-popconfirm>
      </template>

      </n-drawer-content>


    </n-drawer>


</template>



<style scoped>
.calendar-container {
  width: 100%;
  margin: 0 auto;
  font-family: Arial, sans-serif;
}


.calendar-header button {
  padding: 5px 10px;
  cursor: pointer;
}

.calendar-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 10px;
}

.weekday {
  text-align: center;
  padding:5px 10px;
  background-color: #f0f0f0;
}

.calendar-day {
  min-height: 100px;
  padding: 0px;
  border-radius: 10px;
  background-color: #fff;
}

.calendar-day.current-month {
  background-color: #fff;
}

.calendar-day:not(.current-month) {
  background-color: #f9f9f9;
  color: #aaa;
}

.calendar-day.today {
  border: 2px solid #d95b74;
  border-radius: 10px;
}

.day-number {
  font-weight: bold;
  margin-bottom: 5px;
  border-bottom: 1px solid #eee;
  width: 100%;
  padding: 5px 5px;
}

.todo-item {
  background-color: #e3f2fd;
  padding: 2px 5px;
  margin: 5px;
  border-radius: 3px;
  cursor: move;
  font-size: 12px;
}



.todo-form {
  margin-top: 20px;
  display: flex;
  gap: 10px;
}

.todo-form input, .todo-form select {
  padding: 8px;
  flex-grow: 1;
}

.todo-form button {
  padding: 8px 15px;
  background-color: #8945c3;
  color: white;
  border: none;
  cursor: pointer;
}

.todo-form button:hover {
  background-color: #8945c3;
}
</style>